package com.concurrent.data.thread.controller;

import com.concurrent.data.thread.common.Result;
import com.concurrent.data.thread.entity.Goods;
import com.concurrent.data.thread.service.GoodsService;
import com.concurrent.data.thread.utils.RedisUtil;
import com.concurrent.data.thread.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author 哲思小辉
 * @version 1.0.0
 * @ClassName GoodsController.java
 * @Description 商品控制类
 * @Param
 * @createTime 2020年03月25日 20:35:00
 */
@Component
@RestController
@RequestMapping("goods")
@Api(value = "商品控制类", tags = "商品控制类")
@Slf4j
public class GoodsController {
    /**
     * 服务对象
     */
    @Autowired
    private GoodsService goodsService;

    public volatile static int count = 0;


    @PostMapping("addGoods")
    @ApiOperation(value = "新增商品", notes = "新增商品")
    public Result<Goods> addGoods(@RequestBody Goods goods) {
        RLock rLock = RedisUtils.getRLock(goods.getName());
        boolean islock = false;
        try {
            islock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (islock) {
                log.info("\n{} --> 获取锁成功", Thread.currentThread().getName());
                goods = this.goodsService.insert(goods);
                return Result.success(goods);
            }
        } catch (Exception e) {
            log.info("\n{} --> 获取锁失败:{}", Thread.currentThread().getName(), e);
        } finally {
            if (islock) {
                rLock.unlock();
            }
        }
        log.info("\n{} --> 获取锁失败", Thread.currentThread().getName());
        return Result.failure("服务暂时无法加载。。。");
    }

    @PostMapping("getGoods")
    @ApiOperation(value = "获取商品", notes = "获取商品")
    public Result<Goods> addGoods(Integer goodsId) {
        Goods goods = this.goodsService.queryById(goodsId);
        return Result.success(goods);
    }
}